const crypto = require('crypto');
const router = require('koa-router')();
const mySQLHelper = require('../libs/MySQLHelper');
const scripts = require('../configs/scripts/msyql');

router.prefix('/api/user');

/**
 * 登录验证。
 */
router.post('/logon', async (ctx, next) => {
    let params = ctx.request.body;
    let hash = crypto.createHash('md5');

    hash.update(params.password);
    params.password = hash.digest('hex').toUpperCase();

    await mySQLHelper.query(scripts.LogonValid, params)
        .then(rs => {
            if (rs.datas[0]) {
                let now = new Date();
                rs.datas[0].expDate = new Date(now.getTime() + 30 * 60 * 1000);

                ctx.session.user = rs.datas[0];
            }

            ctx.body = rs;
        }, reason => ctx.body = reason);
});

/**
 * 单点登录处理。
 */
router.post('/slogon', async (ctx, next) => {
    let params = ctx.request.body;
    let hash = crypto.createHash('md5');

    hash.update(params.tenantGuid + params.account + params.time + params.rnd);

    let md5Rs = hash.digest('hex').toUpperCase();

    if (md5Rs == params.md5) {
        await mySQLHelper.query(scripts.SLogonValid, params).then(rs => {
            if (rs.datas[0]) {
                let now = new Date();
                rs.datas[0].expDate = new Date(now.getTime() + 30 * 60 * 1000);
                
                ctx.session.user = rs.datas[0];

                ctx.body = rs;
            }else{
                await (ctx.body = {
                    at: new Date(),
                    success: false,
                    message: '用户登录验证失败！'
                });
            }
        });
    } else {
        await (ctx.body = {
            at: new Date(),
            success: false,
            message: '用户登录验证失败！'
        });
    }
});

router.post('/logoff', async (ctx, next) => {
    ctx.session.user = null;
    ctx.session = {};

    await (ctx.body = {
        isLogIn: false
    });
});

module.exports = app => {
    app.use(router.routes(), router.allowedMethods());

    return router;
}